package org.frame.factory;

import org.frame.myaop.ChainManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class JdkDynamicProxyHandler {
    public static InvocationHandler getHandler(Class clazz,IAddFeature addFeature){
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                Object obj = clazz.getDeclaredConstructor().newInstance();

                Object ret = null;
                if(addFeature != null){
                    Map<String,Object> infos = new HashMap<>();
                    addFeature.before(infos);
                    ret = method.invoke(obj,objects);
                    addFeature.after(infos);
                }else{
                    ret = method.invoke(obj,objects);
                }

                return ret;
            }
        };
        return handler;
    }
    public static InvocationHandler getHandler(ChainManager cm){

        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                cm.beforeExecute();
                Object ret= method.invoke(cm.getTarget(),objects);
                cm.afterExecute();
                return ret;
            }
        };
        return handler;
    }
    public static Object getProxyObject(InvocationHandler handler,Object obj){
        Class clazz = obj.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),handler);
    }
    protected static Object getProxyObject(InvocationHandler handler,Class clazz){
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),handler);
    }
}
